﻿using System;
using System.Collections;
using System.Reflection;
using System.Configuration;
namespace GaiNo.Core.Data
{
    internal class SqlMapper: ISqlMapper
    {
        private Hashtable _maps = new Hashtable();        
        public SqlMapper(Hashtable maps)
        {
            _maps = maps;
        }
        #region IMapper 成员

        #endregion

        #region ISqlMapper 成员

        public int Create(object type)
        {
            string sql = watch(type, getSql(type, "Insert"));
            return SqlHelper.ExecuteNonQuery(sql);
        }

        public int Update(object type)
        {
            string sql = watch(type, getSql(type, "Update"));
            return SqlHelper.ExecuteNonQuery(sql);
        }
        public int Delete(object type)
        {
            string sql = watch(type, getSql(type, "Delete"));
            return SqlHelper.ExecuteNonQuery(sql);
        }

        #endregion
        private string getSql(object type, string t)
        {
            string key = type.GetType().FullName;
            if (_maps == null || !_maps.Contains(key))
                throw new Exception("Mapping error!");
            Map curd = (Map)_maps[key];
            if (t == "Insert")
                return curd.Create;
            else if (t == "Update")
                return curd.Update;
            else if (t == "Delete")
                return curd.Delete;
            return null;
        }
        private string watch(object type, string sql)
        {
            if (type == null || string.IsNullOrEmpty(sql))
                return null;

            string result = sql;
            Type myType = type.GetType();
            //Assembly asm = myType.Assembly;//Assembly.LoadFrom(myType.Assembly.FullName + ".dll");
            //Type myClass = asm.GetType(myType.FullName);
            PropertyInfo[] ps = myType.GetProperties();
            foreach (PropertyInfo p in ps)
            {
                if (isIn(p.PropertyType.FullName))
                {
                    object value = p.GetValue(type, null);
                    string strValue = string.Empty;
                    if (value != null)
                        strValue = value.ToString();
                    result = result.Replace("$@" + p.Name + "$", string.IsNullOrEmpty(strValue) ? "" : strValue);
                }
            }
            return result;
        }
        private bool isIn(string s)
        {
            string[] strs = new string[] { "System.Int32", "System.Single", "System.Double", "System.Char", "System.Decimal", "System.String", "System.Boolean", "System.DateTime" };
            foreach (string str in strs)
            {
                if (str.Equals(s))
                    return true;
            }
            return false;
        }

    }
}
